package db.dao;

import db.Database;
import db.entities.Conta;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public final class ContaDAO {
    
    public static int getRowCount() {
        return Database.getTableRowCount("accounts");
    }
    
    public static Conta getAccountById(int id) {
        Conta acc = null;
        try {
            Connection conn = Database.getInstance().getConnection();
            String sql = "select idaccount, nome, servidor, porta, usuario, senha from accounts where idaccount = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            if(rs.next()) {
                acc = new Conta();
                acc.setId(rs.getInt("idaccount"));
                acc.setNome(rs.getString("nome"));
                acc.setServidor(rs.getString("servidor"));
                acc.setPorta(rs.getInt("porta"));
                acc.setUsuario(rs.getString("usuario"));
                acc.setSenha(rs.getString("senha"));
            }
            rs.close();
            ps.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return acc;
    }
    
    public static ArrayList<Conta> getAllAccountsByArraylist() {
        ArrayList<Conta> lista = new ArrayList<Conta>();
        try {
            Connection conn = Database.getInstance().getConnection();
            String sql = "select idaccount, nome, servidor, porta, usuario, senha from accounts";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while(rs.next()) {
                Conta acc = new Conta();
                acc.setId(rs.getInt("idaccount"));
                acc.setNome(rs.getString("nome"));
                acc.setServidor(rs.getString("servidor"));
                acc.setPorta(rs.getInt("porta"));
                acc.setUsuario(rs.getString("usuario"));
                acc.setSenha(rs.getString("senha"));
                lista.add(acc);
            }
            rs.close();
            stmt.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }        
        return lista;
    }
    
}
